import { Text, View, StyleSheet, TouchableWithoutFeedback, FlatList, Switch } from 'react-native'
import React, { Component, useState, useEffect } from 'react'
import { connect } from 'react-redux'
import { asyncGetGroupList, SetGroupMsg } from "../../redux/features/appSlice"
import { pTx } from "../../utils/dimensions"
import { Cell, Badge } from '@pingtou/rn-vant'
import { formatGroupMsg } from "../../utils/formatFriendMsg"
import { showModal } from "../../components/rootSiblings/showModal"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm, { flags } from "realm"
import httpApi from "../../api"
import DeleteContact from "../../components/rootSiblings/deleteContact"
import Avatar from "../../components/avatar"
import realmValue from "../../utils/realmValue"
import IconFont from '@pingtou/rn-vant-icons'
const groupManage = (props) => {
    const [group] = useState(props.route.params)
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];

    const groupList = useQuery(schemaName.GroupList, Group => {
        return Group.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`);
    })

    const groupInfo = useQuery(schemaName.GroupInfo, Info => {
        return Info.filtered(`Id == ${group.G} and UserId == ${userInfo.Id}`);
    })[0];

    const [isEnabled, setIsEnabled] = useState([0, 8, 16].indexOf(groupInfo.Status) !== -1 ? false : true)


    const groupMembers = useQuery(schemaName.GroupMembers, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`)
    })

    const groupMsgLis = useQuery(schemaName.GroupMsgLis, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`).sorted('T', true)
    })

    const groupMsgLisJoinUnread = useQuery(schemaName.GroupMsgLis, groupMsg => {
        return groupMsg.filtered(`G == ${group.G} and UserId == ${userInfo.Id} and MT == 61 and  Unread == 1`).sorted('T', true)
    })

    const groupAdmins = useQuery(schemaName.GroupAdmins, admins => {
        return admins.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`)
    })

    const isAdmins = () => userInfo.Id == groupInfo?.OwnerId

    const toggleSwitch = async () => {
        setIsEnabled(previousState => !previousState);
        const res = await httpApi.setAllowSend({ groupId: group.G, status: isEnabled ? 0 : 1 })
        if (res.code == 20) {
            realm.write(() => {
                if (!isEnabled) {
                    groupInfo.Status = groupInfo.Status == 0 ? 2 : groupInfo.Status == 8 ? 10 : 18
                } else {
                    groupInfo.Status = groupInfo.Status == 2 ? 0 : groupInfo.Status == 10 ? 8 : 16
                }
            })
        } else {
        }
    }

    const sendGroupDisband = async () => {
        try {
            const res = await httpApi.sendGroupDisband({ groupId: group.G, msgType: 99 })
            if (res.code == 20) {
                props.navigation.navigate('chat')
                setTimeout(() => {
                    realm.write(() => {
                        realm.delete(groupList);
                        realm.delete(groupMembers);
                        realm.delete(groupMsgLis);
                        realm.delete(groupAdmins);

                    })
                })
                props.navigation.navigate('chat')
            }

        } catch (error) {
        }
    }
    return (
        <View style={styles.page}>
            <View >
                <Cell.Group>
                    <Cell title="查找进群申请" onPress={() => isAdmins() && props.navigation.navigate('groupJoinReply', group)} value={
                        <View style={styles.right}>
                            {groupMsgLisJoinUnread.length > 0 && <Badge dot={!!groupMsgLisJoinUnread.length} />}
                            {<IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    } center />
                    <Cell title="设置加群方式" onPress={() => isAdmins() && props.navigation.navigate('setGroupJoin', group)} center value={
                        <View style={styles.right}>
                            {isAdmins() && <IconFont name="arrow" size={pTx(16)} />}
                        </View>
                    } />
                    {isAdmins() && <Cell title="全员禁言" center value={
                        <Switch
                            trackColor={{ false: "#767577", true: "rgba(68, 225, 240, 1)" }}
                            thumbColor={isEnabled ? "rgba(51, 225, 144, 1)" : "#f4f3f4"}
                            ios_backgroundColor="#3e3e3e"
                            onValueChange={toggleSwitch}
                            value={isEnabled}
                        />

                    } />}
                    <Cell title="群管理员" onPress={() => props.navigation.navigate('groupAdmins', group)} center value={
                        <View style={styles.right}>
                            <IconFont name="arrow" size={pTx(16)} />
                        </View>
                    } />
                </Cell.Group>
            </View>
            {isAdmins() &&
                <View style={styles.foot}>
                    <TouchableWithoutFeedback
                        onPress={() => showModal(<DeleteContact operation={
                            [
                                { text: '解散该群聊', onPress: () => sendGroupDisband() },
                            ]
                        } />)}
                    >
                        <View style={styles.footRow}>
                            <Text style={styles.sendMessage} >解散该群聊</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
            }
        </View>
    )
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
    asyncGetGroupList,
    SetGroupMsg
}

export default connect(mapStateToProps, mapDispatchToProps)(groupManage)

const styles = StyleSheet.create({
    headerRightIcon: {
        paddingRight: pTx(15),
    },
    page: {
        flex: 1,
        backgroundColor: "#EDEDED"
    },
    FlatListItem: {
        paddingHorizontal: pTx(12),
        paddingVertical: pTx(6),
        alignSelf: "center"
    },
    Avatar: {
        width: pTx(50),
        height: pTx(50),
        borderRadius: pTx(4),
    },
    userName: {
        textAlign: "center",
        width: pTx(50),
    },
    foot: {
        marginTop: pTx(10),
        backgroundColor: "#ffffff"
    },
    footRow: {
        height: pTx(50),
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    },
    sendMessage: {
        marginLeft: pTx(3),
        fontSize: pTx(16),
        color: "#ee0a24",
        textAlign: "center"
    },
    applyMsg: {
        minWidth: pTx(18),
        paddingHorizontal: pTx(5),
        paddingVertical: pTx(1),
        borderRadius: pTx(38),
        textAlign: "center",
        color: "#fff",
        fontWeight: "500",
        fontSize: pTx(10),
        backgroundColor: "#ee0a24"
    },
    right: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    }
})